package com.jie.commonlib.network.http

import android.text.TextUtils
import com.jie.commonlib.GlobalConfig
import com.jie.commonlib.common.FolderManager.downloadPath
import com.jie.commonlib.support.sputils.UserInfoUtils
import com.net.okhttphelper.OkHttpHelper
import com.net.okhttphelper.download.DownloadListener
import com.net.okhttphelper.http.HttpConfig
import com.net.okhttphelper.http.RequestParams
import com.net.okhttphelper.upload.UploadListener

/**
 * 网络请求封装入口
 * @author jie
 */
object HttpHelper {
    private val mOkHttpHelper: OkHttpHelper = OkHttpHelper.getInstance()

    /**
     * 触发请求
     * @param requestParams 请求参数
     * @param callBack 请求回调
     * @param <T> 返回实体泛型
    </T> */
    fun <T> enqueue(requestParams: RequestParams, callBack: HttpCallBack<T?>?) {
        enqueue(requestParams, callBack, null)
    }

    /**
     * 触发请求
     * @param requestParams 请求参数
     * @param callBack 请求回调
     * @param uploadListener 上传进度监听
     * @param <T> 返回实体泛型
    </T> */
    fun <T> enqueue(
        requestParams: RequestParams,
        callBack: HttpCallBack<T?>?,
        uploadListener: UploadListener?
    ) {
        val params = dealParam(requestParams)
        mOkHttpHelper.enqueue(params, HttpCallBackHandle(callBack), uploadListener)
    }
    /**
     * 下载文件（带下载进度监听）
     * @param requestParams 请求参数
     * @param callBack 下载回调
     * @param downloadListener 文件下载到本地文件夹地址
     */
    @JvmOverloads
    fun download(
        requestParams: RequestParams,
        callBack: HttpCallBack<String?>?,
        downloadListener: DownloadListener? = null
    ) {
        val params = dealParam(requestParams)
        mOkHttpHelper.download(params, HttpCallBackHandle(callBack), downloadListener)
    }

    /**
     * 添加公共的请求参数
     */
    private fun dealParam(requestParams: RequestParams): RequestParams {
        // 添加请求头
        val accessToken = UserInfoUtils.getInstance().accessToken
        return if (!TextUtils.isEmpty(accessToken)) {
            requestParams.newBuilder()
                .putHeader(HttpCommonConstant.TOKEN_PARAM, accessToken)
                .build()
        } else requestParams
    }

    /**
     * 取消一个请求
     * @param tag 请求标识
     */
    fun cancel(tag: String?) {
        mOkHttpHelper.cancel(tag)
    }

    /**
     * 取消所有请求
     */
    fun cancelAll() {
        mOkHttpHelper.cancelAll()
    }

    init {
        // 配置参数
        val baseUrl = HttpCommonConstant.BASE_URL
        val saveDirPath = downloadPath
        val httpConfig = HttpConfig.Builder()
            .setShowLog(GlobalConfig.isShowLog)
            .setReadTimeout(HttpCommonConstant.HTTP_REQUEST_MAX_WAIT_TIME)
            .setConnectTimeout(HttpCommonConstant.HTTP_REQUEST_MAX_WAIT_TIME)
            .build(baseUrl, saveDirPath)
        mOkHttpHelper.init(httpConfig)
    }
}